import sys

import cv2
import json
import time
from Config import getConfig
import threading


def delaySearchFace(socket, GrayFace):
    cv2.imwrite('messigray.png', GrayFace)
    with open('messigray.png', 'rb') as image:
        lines = image.read()
    socket.socketSend(lines, 2)
    ru = socket.socketReceive()
    if ru[0] == 1:
        name = 'not found'
    else:
        data = json.loads(str(ru[3], encoding="utf8"))
        name = data["face_name"]
        result = data["result"]
        # print(result)
        if result == "record complete":
            print(name + "登记成功")
        elif result == "record in within 10 minutes":
            print(name + "十分钟内登记过！")


class faceOperate:
    def __init__(self) -> None:
        pass

    @staticmethod
    def addFace(socket, cam, entity_id):
        data = {'entity_id': entity_id}
        socket.socketSend(bytes(json.dumps(data).encode('utf-8')), 1)
        com, dataSize, guid, name = socket.socketReceive()
        if com == 1:
            return '添加失败：' + data['entity_id'] + '存在'
        elif com == 0:
            name = str(name, encoding="utf8")
            print('添加' + name + '数据成功')
            frame, GrayFace, no = cam.cameraRun()
            cv2.imshow('234', frame)

            while True:
                if type(GrayFace) != list:
                    cv2.imwrite('messigray.png', GrayFace)
                    with open('messigray.png', 'rb') as image:
                        lines = image.read()
                    socket.socketSend(lines, 1)
                    com, dataSize, guid, data = socket.socketReceive()
                    if com == 3:
                        break
                    else:
                        data = json.loads(str(data, encoding="utf8"))
                        print(data["msg"])
                        pass
            return str(socket.socketReceive()[3], encoding="utf8")

    @staticmethod
    def SearchFace(socket, cam):
        i = 0
        while True:
            frame, GrayFace, faces = cam.cameraRun()
            cv2.imshow('234', frame)
            if cv2.waitKey(5) & 0xFF == ord('q'):
                cam.cameraClose()
                sys.exit()
                socket.socketclose()

            if type(GrayFace) != list:
                thread = threading.Thread(target=delaySearchFace, args=(socket, GrayFace,))
                thread.daemon = True
                if thread.is_alive():
                    pass
                else:
                    thread.start()
